import sys, math
import urllib2
from BeautifulSoup import BeautifulSoup
from getKeyStats import *
import yaml
import time
from datetime import datetime

# Used to control Print statements
DEBUG=False


SELL="Sell"
BUY="Buy"

#Get the list of Tickers from Config File
def getTickers(configs):
  tickerList=getValueFromConfigs(configs,"tickerList")
  if ( DEBUG ):
    print "Ticker list is " , tickerList
  return tickerList

def getValueFromConfigs(configs, key):
  if ( DEBUG ):
    print "configs[ " , key , " ]=" , configs[key]
  return configs[key]
  

#Is the Company Fairly Valued
def isFairlyValued( pegRatio, optimalPegRatio ):
  if pegRatio <= optimalPegRatio: 
     return True
  else:
     print"*** isFairlyValued: pegRatio is " , pegRatio ," optimal Is " , optimalPegRatio
     return False

# is the company Highly leveraged?
def isHighlyLevered( debtToEquity, optimalDebtToEquity):
  
  if ( debtToEquity=="N/A"):
    # No Debt
    return False
  else:
    if ( float( debtToEquity ) > optimalDebtToEquity ):
      print "*** DebtToEquity is " , float( debtToEquity) , " optimal is " , optimalDebtToEquity
      return True
    else:
      return False
   

#Is a high Percentage company - Used for Growth and Yield. Pass in Key as 3rd arg
def isHighPct( pct, optimalPct, key ):
  
  # If set to optimalPct is set zero, return true.  This is an switch to skip this routine.
  if ( optimalPct == 0 ):
    print "*** isHighPct: Ignoring " , key , " since optimalPct is zero. pct is " , pct , " optimal Is " , optimalPct
    return True
  
  if ( pct=="N/A"):
    # No Growth
    print"*** isHighPct: key is " , key , " pct is " , pct ," optimal Is " , optimalPct
    return False

  # Strip out the %
  pct=pct.replace('%','')
  if ( float(pct) >= optimalPct ) : 
     return True
  else:
     print"*** isHighPct: Key is " , key , " pct is " , pct ," optimal Is " , optimalPct 
     return False



def getRecommendation( configs, ticker):
  recommendation="SELL"
  
  keyStats , keyCount =getKeyStats(ticker,DEBUG)
  if ( keyCount == 0 ):
    print "*** Unable to get statistics for  " , ticker  ," *** "
    return
  
  #print "getRecommendation: getValueFromConfigs " , getValueFromConfigs(configs,"PEG_RATIO_KEY")
  #print "getRecommendation: getValueFromKey: " , getValueFromKey( keyStats, getValueFromConfigs(configs,"PEG_RATIO_KEY"))
  pegRatio=float( getValueFromKey( keyStats, getValueFromConfigs(configs,"PEG_RATIO_KEY")) )
  if (DEBUG):
    print "pegRatio is ", pegRatio

  # If there is no debt, this works. If there is debt, say XOM fails because its says
  # string 3.6B etc
  debtToEquity=getValueFromKey( keyStats , getValueFromConfigs(configs,"DEBT_TO_EQUITY_KEY") )
  if (DEBUG):
    print "debtToEquity is ", debtToEquity

  # Replace %. If NA value will be 0.
  qRevGrowth=getValueFromKey( keyStats , getValueFromConfigs(configs,"Q_REV_GROWTH_KEY") )
  if (DEBUG):
    print "qRevGrowth is ", qRevGrowth

  # Replace %. If NA value will be 0.
  divYield=getValueFromKey( keyStats , getValueFromConfigs(configs,"YIELD_KEY") )
  
  print "pegRatio is ", pegRatio , " debtToEquity is ", debtToEquity, " qRevGrowth is ", qRevGrowth ," yield is ", divYield

  # Set Optimal Valeues from Configs
  optimalPegRatio=getValueFromConfigs( configs, "optimalPegRatio")
  optimalDebt=getValueFromConfigs( configs, "optimalDebt")
  optimalDebtToEquity=getValueFromConfigs( configs, "optimalDebtToEquity")
  optimalQRevGrowth=getValueFromConfigs( configs, "optimalQRevGrowth")
  optimalYield=getValueFromConfigs( configs, "optimalYield")

  if ( isFairlyValued(pegRatio, optimalPegRatio)):
    if ( isHighPct( qRevGrowth, optimalQRevGrowth, getValueFromConfigs(configs,"Q_REV_GROWTH_KEY"))):
      if ( isHighPct( divYield, optimalYield , getValueFromConfigs(configs,"YIELD_KEY"))):
        if ( isHighlyLevered( debtToEquity, optimalDebtToEquity ) ):
         recommendation=SELL
        else:
         recommendation=BUY
      
       
  return recommendation

# Perform analysis for a given ticker
#def performAnalysis( configs ,ticker ):
  results , keyCount =getKeyStats(ticker,DEBUG)

  if ( keyCount == 0 ):
    print "*** Unable to get statistics for  " , ticker  ," *** "
    return
  
  eps=float ( getValueFromKey( results, getValueFromConfigs(configs, "EPS_KEY")) ) 
  pe=float ( getValueFromKey( results, getValueFromConfigs(configs,"PE_KEY")) )

  #print "eps=" , eps
  #print "pe=" , pe
  price = eps * pe
  print "Perform Analysis for ticker:" , ticker ," price=" , price , " eps=" , eps , " pe = " , pe

  recommendation=getRecommendation( configs ) 
  print "*** Recommendation for " , ticker  , "is " , recommendation , " *** "


# Start Script
#startTime=time.asctime( time.localtime(time.time() ) )
tstart = datetime.now()
#print "***  Starting Script at ",  startTime

#Load Configs from File.
configs=yaml.load( open("analyzeStock.yaml"))


count=0
for ticker in getTickers(configs):
  count=count+1
  recommendation=getRecommendation( configs, ticker ) 
  print "*** Recommendation for " , ticker  , "is " , recommendation , " *** "
  

#endTime=time.asctime( time.localtime(time.time() ) )
tend = datetime.now()
#print "*** Ending Script at  " , endTime
print "*** Execution time for " , count , " tickers  =" , tend - tstart



